package com.zkq.graduate.interceptor;

import com.zkq.graduate.pojo.Role;
import com.zkq.graduate.pojo.Users;
import com.zkq.graduate.service.UserAndRoleService;
import com.zkq.graduate.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author zhangkaiqiang
 * @Date 2019/9/28  15:52
 * @Description TODO
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	UserAndRoleService userAndRoleService;

	/**
	 * 判断是否携带token,未携带说明未登录,跳转登录页
	 * @param request
	 * @param response
	 * @param handler
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uti=request.getRequestURI();
		Cookie[] cookies=request.getCookies();
		Map<String,Object> verifyResultMap=new HashMap<>(16);
		for (Cookie cookie : cookies) {
			if(Objects.equals("token",cookie.getName())){
				String token=cookie.getValue();
				if(StringUtils.isNotBlank(token)){
					// 验证客户端携带的token
					verifyResultMap=JwtUtil.verifyJwt(token);
					if(verifyResultMap!=null){
						// 置入request中用户的相关属性,便于后序操作
						String account= (String) verifyResultMap.get("account");
						request.setAttribute("id",verifyResultMap.get("id"));
						request.setAttribute("account",account);
						// 得到用户的角色信息
						Users users=Users.builder()
								.account(account)
								.build();
						List<Role> roleList=userAndRoleService.findRoleByUser(users);
						request.setAttribute("role",roleList);
						JwtUtil.refreshToken(request,response,verifyResultMap);
						return true;
					}
				}
				request.getRequestDispatcher("/login.html").forward(request,response);
				return false;
			}
		}
		return false;
	}
}
